import MsgCenter from './MsgCenter'

/**
 * 消息会话的封装
 */
class MsgSession {

    constructor() {
        this.sessionId = null
        this.createTimelet = null
        this.sessionText = null
        this.notReadCount = 0
        this.chatType = null
    }

    /**
     * 消息产生的session
     * @param msgObject
     * @param notRead
     * @param sessionId
     * @returns {MsgSession}
     */
    static msgToSession(msgObject,notRead,sessionId){
        let msgSession = new MsgSession()
        msgSession.sessionId = sessionId
        msgSession.targetId = msgObject.fromuserid
        if( msgSession.sessionId ==  msgObject.fromuserid){
            msgSession.targetId = msgObject.touserid
        }
        msgSession.createTimelet = msgObject.createtime
        if (msgObject.type == MsgCenter.MsgType.VOICE) {
            msgSession.sessionText = '[语音]'
        } else if (msgObject.type == MsgCenter.MsgType.IMAGE) {
            msgSession.sessionText = '[图片]'
        }else if(msgObject.type == MsgCenter.MsgType.TEXT){
            msgSession.sessionText = msgObject.content
        }
        //群聊的话 要带上名字
        if (msgObject.chattype == MsgCenter.chatType.GROUP) {
            msgSession.sessionText = msgObject.fromusername + ":" + msgSession.sessionText
        }
        msgSession.createTime = msgObject.createtime
        msgSession.chatType = msgObject.chattype
        //未读消息累计
        if (notRead) {
            msgSession.notReadCount = 1
        }
        return msgSession
    }

    /**
     * 同步消息会话
     * 1-新消息过来 计算已读取 未读取
     * 2-置顶新消息
     */
    static pushSession(sessionMap, msgSession) {
        let temSession =  sessionMap[msgSession.sessionId]
        if(temSession&&temSession.notReadCount){
            msgSession.notReadCount += temSession.notReadCount
        }
        //修改
        sessionMap[msgSession.sessionId] = msgSession
        //排序
        let sessionList = Object.values(sessionMap)
        sessionList.sort((a, b) => a.createTimelet - b.createTimelet)
        return sessionList
    }



    /**
     * 合并session 一般第一次离线加载
     * //TODO 这里要判断谁的时间更近
     * @param sessionMap
     * @param sessions
     */
    static mergeSessions(sessionMap, msgSessions) {
        for (let i = 0, j=msgSessions.length; i <j; i++) {
            let msgSession = msgSessions[i]
            //修改
            sessionMap[msgSession.sessionId] = msgSession
        }
        //排序
        let sessionList = Object.values(sessionMap)
        sessionList.sort((a, b) => a.createTimelet - b.createTimelet)
        return sessionList
    }


}

export default MsgSession